﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Reflection;
using System.IO;
using System.Xml.Schema;

namespace Accountability4net.FileMonengineProvider
{
    public class XmlFileStorage
    {

        public XmlFileStorage()
        {

        }

        private XmlDocument document_;
        private XmlDocument Document
        {
            get
            {
                if (document_ == null)
                {
                    Validate();
                }
                return document_;
            }
        }

        private void Validate()
        {
            document_ = new XmlDocument();
            string codeBaseDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().CodeBase);
            document_.Load(Path.Combine(codeBaseDirectory, "monengine4net.xml"));
            document_.Schemas.Add(null, Path.Combine(codeBaseDirectory, "monengine4net.xsd"));
            document_.Validate(HandleValidationEvent);
        }

        private void HandleValidationEvent(object src, ValidationEventArgs e)
        {
            throw new Exception("Not valid");
        }

        public void Save()
        {
            string codeBaseDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().CodeBase);
            document_.Save(new Uri(Path.Combine(codeBaseDirectory, "monengine4net.xml")).LocalPath);
        }

        public XmlNode CreateElement(string name)
        {
            return Document.CreateElement(name); 
        }
        
        public XmlNode SelectSingleNode(string xpath)
        {
            return SelectSingleNode(Document, xpath);
        }

        public XmlNode SelectSingleNode(XmlNode node, string xpath)
        {
            return node.SelectSingleNode(xpath, NamespaceManager);
        }

        public XmlNodeList SelectNodes(string xpath)
        {
            return SelectNodes(Document, xpath);
        }

        public XmlNodeList SelectNodes(XmlNode node, string xpath)
        {
            return node.SelectNodes(xpath, NamespaceManager);
        }

        private XmlNamespaceManager namespaceManager_;
        public XmlNamespaceManager NamespaceManager
        {
            get
            {
                if (namespaceManager_ == null)
                {
                    namespaceManager_ = new XmlNamespaceManager(Document.NameTable);
                    namespaceManager_.AddNamespace("x", "http://monengine4net.4thex.com/XMLSchema");
                    namespaceManager_.AddNamespace("xs", "http://www.w3.org/2001/XMLSchema");
                    namespaceManager_.AddNamespace("ms", "xmlns:ms='urn:schemas-microsoft-com:xslt'");
                }
                return namespaceManager_;
            }
        }


    }
}
